package com.jian.controller;

import com.jian.common.BaseResponse;
import com.jian.common.ErrorCode;
import com.jian.common.ResultUtils;
import com.jian.domain.Entrust;
import com.jian.requests.CourierRequestBody;
import com.jian.responses.EntrustResponse;
import com.jian.service.EntrustService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/entrusts")
public class EntrustController {

    @Autowired
    private EntrustService entrustService;


    @GetMapping("/{id}")
    public BaseResponse getEntrustById(@PathVariable("id") Long id) {
        Entrust entrust = entrustService.getById(id);
        if (entrust == null) {
            return ResultUtils.Error(ErrorCode.PARAM_ERROR, "该邮寄单号id不存在");
        }
        return ResultUtils.Success(entrust);
    }

    @GetMapping()
    public BaseResponse getEntrustAll(@RequestParam String token) {
        List<EntrustResponse> entrusts = entrustService.getEntrustsFromRule(token);
        return ResultUtils.Success(entrusts);
    }

    @PostMapping()
    public BaseResponse SaveEntrust(@RequestBody Entrust entrust) {
        if (entrustService.addEntrustOnce(entrust))
            return ResultUtils.Success();
        return ResultUtils.Error(ErrorCode.SAVE_ERROR, "寄件信息存储失败");
    }

    @PostMapping("/update")
    public BaseResponse updateEntrust(@RequestBody Entrust entrust) {
        boolean once = entrustService.updateEntrustOnce(entrust);
        if (once)
            return ResultUtils.Success();
        return ResultUtils.Error(ErrorCode.UPDATE_ERROR, "entrust修改表失败了");
    }

    @PostMapping("/courier")
    public BaseResponse courierUpdateEntrust(@RequestBody CourierRequestBody courier) {
        if (!entrustService.courierUpdateEntrust(courier)) {
            return ResultUtils.Error(ErrorCode.UPDATE_ERROR, "mybatis更新失败了");
        }
        return ResultUtils.Success();
    }

    @PostMapping("/complete")
    public BaseResponse userComplete(@RequestBody CourierRequestBody requestBody){
        if (!entrustService.userComplete(requestBody)) {
            return ResultUtils.Error(ErrorCode.UPDATE_ERROR, "mybatis删除失败了");
        }
        return ResultUtils.Success();
    }

}
